/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include "apr_event.h"

static apr_status_t
apr_event_timer_pool_cleanup(void *baton)
{
    apr_event_timer_t *elem = (apr_event_timer_t *)baton;
    apr_event_loop_t *loop = elem->loop;

    apr_thread_mutex_lock(loop->mtx);
    APR_RING_REMOVE(elem, link);
    apr_thread_mutex_unlock(loop->mtx);

    return APR_SUCCESS;
}

void
apr_event_register_timer(apr_event_loop_t * loop,
                         apr_event_timer_cb_t cb,
                         void *baton, 
                         apr_time_t relative_time,
                         apr_pool_t *shutdown_pool)
{
    apr_event_timer_t *elem = NULL;
    apr_event_timer_t *ep = NULL;
    int inserted = 0;
    apr_time_t t = apr_time_now() + relative_time;

    apr_thread_mutex_lock(loop->mtx);

    APR_RING_CHECK_CONSISTENCY(&loop->timer_ring, apr_event_timer_t, link);

    elem = (apr_event_timer_t *) apr_pcalloc(shutdown_pool, sizeof(apr_event_timer_t));

    APR_RING_ELEM_INIT(elem, link);
    elem->expires = t;
    elem->cb = cb;
    elem->baton = baton;
    elem->pool = shutdown_pool;
    elem->loop = loop;
    apr_pool_cleanup_register(elem->pool, elem, apr_event_timer_pool_cleanup, apr_pool_cleanup_null);

    APR_RING_CHECK_CONSISTENCY(&loop->timer_ring, apr_event_timer_t, link);

    /* pqXXXXXX: skiplist would be a nice optimization here. */
    if (!APR_RING_EMPTY(&loop->timer_ring, apr_event_timer_t, link)) {
        ep = APR_RING_FIRST(&loop->timer_ring);
        while (inserted == 0 &&
               ep != APR_RING_SENTINEL(&loop->timer_ring, apr_event_timer_t, link))
        {
            if (ep->expires < elem->expires) {
                APR_RING_CHECK_CONSISTENCY(&loop->timer_ring, apr_event_timer_t,
                                           link);
                APR_RING_INSERT_BEFORE(ep, elem, link);
                inserted = 1;
                APR_RING_CHECK_CONSISTENCY(&loop->timer_ring, apr_event_timer_t,
                                           link);
            }
            ep = APR_RING_NEXT(ep, link);
        }
    }

    APR_RING_CHECK_CONSISTENCY(&loop->timer_ring, apr_event_timer_t, link);

    if (!inserted) {
        APR_RING_INSERT_TAIL(&loop->timer_ring, elem, apr_event_timer_t, link);
    }

    APR_RING_CHECK_CONSISTENCY(&loop->timer_ring, apr_event_timer_t, link);

    apr_thread_mutex_unlock(loop->mtx);
}


